package com.sims.util;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtil {
	
    public static ComboPooledDataSource dataSource;
	static {
		try {
			dataSource = new ComboPooledDataSource();
			dataSource.setUser("root");
			dataSource.setPassword("pass4321?><M");
			dataSource.setJdbcUrl("jdbc:mysql://118.25.39.42:3306/sims");
			dataSource.setDriverClass("com.mysql.jdbc.Driver");
			dataSource.setInitialPoolSize(5);
			dataSource.setMinPoolSize(5);
			dataSource.setMaxPoolSize(10);
			dataSource.setMaxStatements(100);
			dataSource.setMaxIdleTime(60);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    /**
     * 获取数据源
     * @return 连接池
     */
    public static DataSource getDataSource(){
        return dataSource ;
    }
    
    /**
      * 释放资源
     * @param conn
     * @param st
     * @param rs
     */
     public static void CloseResource(Connection conn,Statement st , ResultSet rs){
         closeResultSet(rs);
         closeStaement(st);
         closeConn(conn);
     }
    
    /**
     * 获取连接
     * @return 连接
     * @throws SQLException 
     */
    public static Connection getConnection() throws SQLException{
        return dataSource.getConnection();
    }
    
    /**
      *释放连接 
     * @param conn
     *     连接
     */
     public static void closeConn(Connection conn){
         if(conn!=null){
             try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                conn = null ;
            }
         }
     }
     
     /**
      * 释放语句执行者
     * @param st
     * 语句执行者
     */
    public static void closeStaement(Statement st){
         if(st!=null){
             try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                st = null ;
            }
         }
     }
    
    /**
     * 释放结果集
     * @param rs
     * 结果集
     */
    public static void closeResultSet(ResultSet rs){
         if(rs!=null){
             try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                rs = null ;
            }
         }
     }

}